import 'package:fish_redux/fish_redux.dart';
import 'package:www.znpigai.teacher/global_store/state.dart';
import 'package:www.znpigai.teacher/utils/http.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'item/state.dart';
import 'state.dart';

Effect<HomeworkListState> buildEffect() {
  return combineEffects(<Object, Effect<HomeworkListState>>{
    Lifecycle.initState: _onInit,
    HomeworkListAction.onLoad: _onLoad,
    HomeworkListAction.onReload: _onReload,
    HomeworkListAction.onDelete: _onDelete,
    HomeworkListAction.onSelectClass: _onSelectClass,
  });
}

void _onInit(Action action, Context<HomeworkListState> ctx) async {
  if (ctx.state.items.length != 0) {
    return; // avoid after loaded
  }

  // load my class list
  ctx.dispatch(HomeworkListActionCreator.loading());
  var url = "/correct/teacher/api/class/list.mvc";
  var result = await Http.get(url);
  ctx.dispatch(HomeworkListActionCreator.loaded());

  if (result.success) {
    ctx.dispatch(HomeworkListActionCreator.classes(result.data));
  } else {
    Util.alertFail(result, ctx.context);
  }

  _onReload(action, ctx);
}

void _onReload(Action action, Context<HomeworkListState> ctx) async {
  if (ctx.state.isLoading) {
    return;
  }

  if (action.payload != null) {
    action.payload(); // callback
  }

  _getHomework(action, ctx, GlobalState.firstPageIndex, GlobalState.pageSize);
}

void _onLoad(Action action, Context<HomeworkListState> ctx) async {
  var pageIndex = ctx.state.pageIndex;
  var total = ctx.state.pageTotal;
  var isLoading = ctx.state.isLoading;
  if (pageIndex >= total || isLoading) {
    return;
  }

  _getHomework(action, ctx, pageIndex, GlobalState.pageSize);
}

void _onDelete(Action action, Context<HomeworkListState> ctx) async {
  bool ok = await Util.showConfirmDialog('删除', '确定要删除？', ctx.context);
  if (!ok) {
    return;
  }

  ctx.dispatch(HomeworkListActionCreator.loading());
  int index = action.payload;
  var item = ctx.state.items[index];
  var url = "/correct/pub/api/exercises/del.mvc";
  final query = {'id': item.id};
  var result = await Http.get(url, query: query);

  ctx.dispatch(HomeworkListActionCreator.loaded());
  if (result.success) {
    ctx.dispatch(HomeworkListActionCreator.deleted(index));
  } else {
    Util.alertFail(result, ctx.context);
  }
}

void _onSelectClass(Action action, Context<HomeworkListState> ctx) async {
  String classId = action.payload;
  ctx.dispatch(HomeworkListActionCreator.selectClass(classId));
  _getHomework(action, ctx, GlobalState.firstPageIndex, GlobalState.pageSize);
}

void _getHomework(Action action, Context<HomeworkListState> ctx, int pageIndex,
    int pageSize) async {
  ctx.dispatch(HomeworkListActionCreator.loading());

  var url = "/correct/teacher/api/homework/list.mvc";
  final query = {
    'cpage': pageIndex,
    'psize': pageSize,
    'classEntityId': ctx.state.currentClassId ?? ''
  };
  var result = await Http.get(url, query: query);

  ctx.dispatch(HomeworkListActionCreator.loaded());
  if (result.success) {
    var responseList = result.data['items'];
    var pageTotal = result.data['pcount'];
    pageIndex += 1;
    List<HomeworkState> items = new List();
    if (responseList != null) {
      responseList.forEach((item) {
        try {
          HomeworkState cellData = new HomeworkState.fromJson(item);
          items.add(cellData);
        } catch (e) {
          // No specified type, handles all
          print(e);
        }
      });
    }

    ctx.dispatch(
        HomeworkListActionCreator.listResult(items, pageTotal, pageIndex));
  } else {
    Util.alertFail(result, ctx.context);
  }
}
